from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash

from flaskr.db import get_db
from flaskr.auth import login_required

bp = Blueprint('room', __name__)

@bp.route('/', methods=('GET', 'POST'))
def index():
    # 获取所有的房间及创作者的信息，传递给模板渲染
    db = get_db()
    rooms = db.execute(
        'SELECT room.id, room.name, user.username FROM room JOIN user ON room.user_id = user.id;'
    ).fetchall()
    return render_template('room/index.html', rooms=rooms)

@bp.route('/search', methods=('GET', 'POST'))
def search():
    if request.method == 'POST':
        # 获取搜索关键词
        keyword = request.form['query']
        if not keyword:
            return redirect(url_for('room.index'))
        db = get_db()
        rooms = db.execute(
            'SELECT room.id, room.name, user.username FROM room JOIN user ON room.user_id = user.id WHERE room.name LIKE ?;', ('%' + keyword + '%',)
        ).fetchall()
        return render_template('room/index.html', rooms=rooms)
    else:
        return redirect(url_for('room.index'))

@bp.route('/join/<int:room_id>', methods=('GET', 'POST'))
@login_required
def join(room_id):
    # 检查room_id是否存在
    db = get_db()
    room = db.execute(
        'SELECT * FROM room WHERE id =?;', (room_id,)
    ).fetchone()
    if room is None:
        flash('房间不存在！')
        return redirect(url_for('room.index'))
    if request.method == 'POST':
        # 获取用户输入的密码
        password = request.form['password']
        if not password:
            flash('必须填写密码！')
            return redirect(url_for('room.join', room_id=room_id))
        if not check_password_hash(room['password'], password):
            flash('密码错误！')
            return redirect(url_for('room.join', room_id=room_id))
        # 保存用户已经登陆的房间ID
        if 'rooms' not in session:
            session['rooms'] = []
        session['rooms'].append(room_id)
        return redirect(url_for('room.chat', room_id=room_id))
    else:
        if room_id in session.get('rooms', []):
            return redirect(url_for('room.chat', room_id=room_id))
        return render_template('room/join.html', room=room)